﻿using Jack.DataScience.Data.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
using Jack.DataScience.Http.Password;

namespace Vav.Data.Payment
{
    /**
     微信支付封装 调用方法：WeChatRequest.BuildWeChatPay(weChatUnifiedOrder, weChatPayment);
     * */

    public class PurchaseReportResponse
    {
        public string timeStamp;
        public string appId;
        public string nonceStr;
        public string package;
        public string signType;
        public string paySign;
    }

    public class WeChatRequest
    {
        public static async Task<PurchaseReportResponse> BuildWeChatPay(WeChatUnifiedOrder weChatUnifiedOrder, string paySecret)
        {
            //参与统一下单签名的参数，除最后的key外，已经按参数名ASCII码从小到大排序
            var stringA = $"appid={weChatUnifiedOrder.appid}&body={weChatUnifiedOrder.body}&mch_id={weChatUnifiedOrder.mch_id}&nonce_str={weChatUnifiedOrder.nonce_str}&notify_url={weChatUnifiedOrder.notify_url}&openid={weChatUnifiedOrder.openid}&out_trade_no={weChatUnifiedOrder.out_trade_no}&spbill_create_ip={weChatUnifiedOrder.spbill_create_ip}&total_fee={weChatUnifiedOrder.total_fee}&trade_type={weChatUnifiedOrder.trade_type}";
            //拼接key
            var unifiedorderSignParam = $"{stringA}&key={paySecret}";
            //MD5加密生成签名
            weChatUnifiedOrder.sign = unifiedorderSignParam.ToMD5Hash().ToUpper();
            //序列化XML
            var payXml = weChatUnifiedOrder.XmlSerialize();
            //统一下单
            var payResultXML = await Unifiedorder(payXml);
            //解析支付请求的参数返回给前端
            var content = ParseXmlContent(payResultXML, paySecret);
            return content;
        }
        /// <summary>
        /// 统一下单
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static async Task<string> Unifiedorder(string xml)
        {
            using (var client = new HttpClient() { BaseAddress = new Uri("https://api.mch.weixin.qq.com") })
            {
                var response = await client.PostAsync("/pay/unifiedorder", new StringContent(xml, Encoding.UTF8, "text/xml"));
                var responseXml = await response.Content.ReadAsStringAsync();
                return responseXml;
            }
        }
        /// <summary>
        /// 解析支付请求的参数返回给前端
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static PurchaseReportResponse ParseXmlContent(string xml, string paySecret)
        {
            var payRes = XDocument.Parse(xml);
            var root = payRes.Element("xml");
            //当return_code 和result_code都为SUCCESS时才有我们要的prepay_id
            if (root.Element("return_code").Value == "SUCCESS" && root.Element("result_code").Value == "SUCCESS")
            {
                var purchase = new PurchaseReportResponse
                {
                    package = "prepay_id=" + root.Element("prepay_id").Value,
                    appId = root.Element("appid").Value,
                    nonceStr = root.Element("nonce_str").Value,
                    signType = "MD5",
                    timeStamp = Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds).ToString(),
                };
                //签名
                var paySignParam = $"appId={purchase.appId}&nonceStr={purchase.nonceStr}&package={purchase.package}&signType={purchase.signType}&timeStamp={purchase.timeStamp}&key={paySecret}";
                purchase.paySign = paySignParam.ToMD5Hash().ToUpper();
                return purchase;
            }
            return null;
        }
    }

}
